<template>
	<view class="mian">
		<uni-forms ref="baseForm" :rules="rules" :modelValue="baseFormData" label-width="120">
			<label class="title_customer">企业名称：<text> {{networkMobileCreateVo?.customer}}</text></label>
			<view class="uni_form">
				<uni-forms-item label="服务商名称" required name="name">
					<uni-easyinput v-model="baseFormData.name" placeholderStyle="font-size:28rpx;"
						placeholder="请输入服务商名称" />
				</uni-forms-item>
				<uni-forms-item label="团队模式" required>
					<view class="team_type">
						<uni-data-checkbox v-model="baseFormData.teamType" :localdata="teamType" />
					</view>
				</uni-forms-item>
				<uni-forms-item label="所属区域" required name="area">
					<AreaAddress ref="addressRef" :address_obj="addressValue" @change="changeAddress"></AreaAddress>
				</uni-forms-item>
				<uni-forms-item label="详细地址" required name="address">
					<uni-easyinput v-model="baseFormData.address" placeholderStyle="font-size:28rpx;"
						placeholder="请输入详细地址" />
				</uni-forms-item>
				<uni-forms-item label="服务区域" required>
					<view class="addressListStr_type" @click="showPicker">
						<view :class="addressListStr||'tip'">
							{{addressListStr||'请选择'}}
						</view>
						<uni-icons type="down" size="14" class="icon_btn" color="rgb(153, 153, 153)"></uni-icons>
					</view>

				</uni-forms-item>
				<!-- 自定义字段 -->
				<view v-for="(item ,index) in baseFormData.fieldVals" :key="index">
					<uni-forms-item
						:label="`${item.name}${item.type==5||item.type==6||item.type==7?'（'+item.imgarr.length+'/'+item.uploadQty+'）':''}`"
						:required="item.required" v-if="!(item.type==6||item.type==5)"
						:name="['fieldVals',index,item.type === 5 || item.type === 6 || item.type === 7 ? 'imgarr' : 'value']"
						:rules="[{ required: item.required, errorMessage: item.tip||'必填' },]">
						<view class="team_type">
							<!-- 文本1 -->
							<uni-easyinput v-model="item.value" v-if="item.type === 1"
								placeholderStyle="font-size:28rpx;" :placeholder="item.tip " />
							<!-- 多行文本2 -->
							<uni-easyinput trim="right" autoHeight v-model="item.value" type="textarea"
								v-if="item.type === 2" placeholderStyle="font-size:28rpx;"
								:placeholder="item.tip||'请输入'" />
							<!-- 单选 3-->
							<uni-data-select v-model="item.value" v-if="item.type === 3 && item.contents.length > 3"
								:localdata="item.contents"></uni-data-select>
							<uni-data-checkbox v-model="item.value" v-else-if="item.type === 3"
								:localdata="item.contents"></uni-data-checkbox>
							<!-- 多选4 -->
							<uni-data-checkbox v-if="item.type === 4" multiple v-model="item.value"
								:localdata="item.contents"></uni-data-checkbox>
							<!-- 图片 5 -->
							<view class="pic_img" v-if="item.type===5">
								<uni-file-picker @select="(files)=>onsuccessImg(item,files)" :auto-upload="false"
									@delete="(file)=>ondeleteImg(item,file)" :imageStyles="imageStyles"
									file-mediatype="image" v-model="item.imgarr" :limit="item.uploadQty"
									file-extname="jpg,jpeg,png" />
							</view>
							<!-- 附件6 -->
							<view class="pic_video" v-if="item.type===6">
								<view class="list_video" v-for="(src,imgIndex) in item.imgarr" :key="imgIndex">
									<view class="box_video_pdf">
										<uni-icons type="closeempty" @click="delete_video(item,imgIndex)"
											class="clear_icon" size="14" color="#fff"></uni-icons>
										<view class="pdf_sty" @click="lookPDF(src.url)">
											PDF
										</view>
									</view>
								</view>
								<view class="btn_uploader" v-if="item.uploadQty>item.imgarr.length">
									<uni-icons type="plusempty" class="icon_plus" size="18" color="#999"></uni-icons>
									<uni-file-picker :limit="item.uploadQty" file-extname="pdf" fileMediatype="all"
										v-model="item.imgarr" :auto-upload="false"
										@select="(file)=>chooseFile(item,file)" />
								</view>
							</view>
							<!-- 视频7 -->
							<view class="pic_video" v-if="item.type===7">
								<view class="list_video" v-for="(src,imgIndex) in item.imgarr" :key="imgIndex">
									<view class="box_video">
										<uni-icons type="closeempty" @click="delete_video(item,imgIndex)"
											class="clear_icon" size="14" color="#fff"></uni-icons>
										<video :src="src.url" :controls="false" :enable-progress-gesture="false"
											:show-center-play-btn="false" class="item_video"></video>
									</view>
								</view>
								<view class="btn_uploader" v-if="item.uploadQty>item.imgarr.length">
									<uni-icons type="plusempty" class="icon_plus" size="18" color="#999"></uni-icons>
									<uni-file-picker fileMediatype="video" :limit="item.uploadQty" file-extname="mp4,mov"
										mode="grid" :auto-upload="false"
										@select="(file)=>chooseVideoImage(item,file)" />
								</view>
							</view>
						</view>
					</uni-forms-item>
				</view>
			</view>
		</uni-forms>
		<view class="tree-picker">
			<ba-tree-picker ref="treePicker" :multiple='true' @select-change="selectChange" title="选择城市"
				:localdata="listData" valueKey="code" textKey="name" childrenKey="children" />
		</view>
		<view class="btn_word">
			<button type="primary" class="btn_bor" @click="onSave">确认创建</button>
		</view>
	</view>
</template>

<script setup lang="ts">
	import {
		ref,
		reactive, onMounted
	} from 'vue';
	import {
		onLoad, onHide
	} from '@dcloudio/uni-app'
	import AreaAddress from '@/components/u-network/AreaAddress.vue'
	import apiAddress from '@/util/network_api/address.js';
	import apiNetwork from '@/util/network_api/network.js'
	import baTreePicker from "@/components/ba-tree-picker/ba-tree-picker.vue"
	import apiUpload from '@/util/network_api/upload.js'
	import _ from "lodash";
	const networkMobileCreateVo = ref()
	const baseForm = ref()
	const listData = ref([])
	const treePicker = ref()
	const addressListStr = ref('')
	const inviteCode = ref('')
	const baseFormData = ref({
		"address": "",
		"area": "",
		"city": "",
		"fieldVals": [],
		"name": "",
		"province": "",
		"teamType": 1,//1团队 2个人
		"serviceAreas": [],
		"town": ""
	})
	const imageStyles = ref({
		"height": 72,	// 边框高度
		"width": 72,	// 边框宽度
		"border": { // 如果为 Boolean 值，可以控制边框显示与否
			"color": "#eee",		// 边框颜色
			"width": "1px",		// 边框宽度
			"style": "solid", 	// 边框样式
			radius: '0px'
		}
	})

	const teamType = ref([{ text: '团队', value: 1 }, { text: '个人', value: 2 }])
	const addressValue = ref()
	const addressRef = ref() //地址组件元素
	const rules = ref({
		name: {
			rules: [{
				required: true,
				errorMessage: '服务商名称不能为空'
			}]
		},
		address: {
			rules: [{
				required: true,
				errorMessage: '详细地址不能为空'
			}]
		},
		area: {
			rules: [{
				required: true,
				errorMessage: '请选择所属地址'
			}]
		}
	})
	// 通过onLoad接收数据
	onLoad((e) => {
		if (e) {
			addCode(e.inviteCode)
			inviteCode.value = e.inviteCode
		}
	})
	onHide(() => {
		uni.hideLoading()
	})
	// 选择图片后触发
	const onsuccessImg = (item, files) => {
		files.tempFiles.filter(o => {
			if (o.size > (item.uploadSize * 1024 * 1024)) {
				uni.showToast({
					icon: 'none',
					title: `图片超过限制大小${item.uploadSize}MB`,
					duration: 1000
				})
			} else {
				item.imgarr.push(o)
			}
		})
	}
	// 图片从列表移除时触发
	const ondeleteImg = (item, file) => {
		item.imgarr = item.imgarr.filter(o => {
			return o.uuid != file.tempFile.uuid
		})
	}
	// 上传视频
	const chooseVideoImage = (item, file) => {
		if (file.tempFiles[0].size > (item.uploadSize * 1024 * 1024)) {
			uni.showToast({
				icon: 'none',
				title: `视频超过限制大小${item.uploadSize}MB`
			})
		} else {
			item.imgarr.push(file.tempFiles[0])
		}
	}
	// 附件上传
	function chooseFile(item, files) {
		files.tempFiles.filter(o => {
			if (o.size > (item.uploadSize * 1024 * 1024)) {
				uni.showToast({
					icon: 'none',
					title: `pdf超过限制大小${item.uploadSize}MB`
				})
			} else {
				item.imgarr.push(o)
			}
		})
	}
	// 查看附件
	const lookPDF = (url) => {
		uni.openDocument({
			filePath: url,
			fileType: 'pdf',
			success: function (res) {
			},
			fail: function (err) {
				uni.showToast({
					icon: 'none',
					title: err
				})
			}
		});
	}
	// 删除视频
	const delete_video = (item, index) => {
		item.imgarr.splice(index, 1)
	}
	onMounted(() => {
		apiAddress.address().then(res => {
			if (res.code == 20000) {
				listData.value = res.data.rows
			}
		})
	})
	// 显示服务地区
	const showPicker = () => {
		treePicker.value._show()
	}
	// 服务区域
	const selectChange = (res) => {
		let serviceAreas = getAddressStringByCode(res);
		baseFormData.value.serviceAreas = serviceAreas
		let str = serviceAreas.map(o => {
			let arr = Object.values(o)
			arr = arr.filter(function (item) {
				return item
			});
			return arr.join('/')
		})
		addressListStr.value = str.join()
	}
	// 根据编码数组获取对应地址
	function getAddressStringByCode(codes) {
		let result = [];
		let currentLevel = listData.value;
		for (let code of codes) {
			let str = {}
			currentLevel.find(item => {
				if (item.code == code) {
					str['province'] = item.name
					str['city'] = ''
					str['area'] = ''
					str['town'] = ''
					str['id'] = ''
				} else {
					item.children.find(item2 => {
						if (item2.code == code) {
							str['province'] = item.name
							str['city'] = item2.name
							str['area'] = ''
							str['town'] = ''
							str['id'] = ''
						} else {
							item2.children.find(item3 => {
								if (item3.code == code) {
									str['province'] = item.name
									str['city'] = item2.name
									str['area'] = item3.name
									str['town'] = ''
									str['id'] = ''
								} else {
									item3.children.find(item4 => {
										if (item4.code == code) {
											str['province'] = item.name
											str['city'] = item2.name
											str['area'] = item3.name
											str['town'] = item4.name
											str['id'] = ''
										}
									})
								}
							})
						}
					})
				}
			});
			result.push(str)
		}
		return result;
	}
	// 
	const changeAddress = (e) => {
		baseFormData.value = {
			...baseFormData.value,
			...addressRef.value.address
		}
	}
	// 保存
	const onSave = async () => {
		let dataData = _.cloneDeep(baseFormData.value)
		await baseForm.value.validate().then(async res => {
			uni.showLoading({
				mask: true,
				title: "加载中..."
			})
			if (baseFormData.value.fieldVals.length > 0) {
				for (let key in dataData.fieldVals) {
					let item = dataData.fieldVals[key]
					item['optVos'] = []
					if (item.type === 4) {
						for (let i = 0; i < item.value.length; i++) {
							let tmp = item.value[i]
							item.optVos.push({ id: null, optValue: tmp })
						}
					} else
						if (item.type === 5 || item.type === 6) {
							for (let i = 0; i < item.imgarr.length; i++) {
								let tmp = item.imgarr[i]
								await apiUpload.uploadOrderFile({ files: tmp.file }).then(res => {
									item.optVos.push({ id: null, optValue: res.data.rows[0] })
								})
							}
						} else
							if (item.type === 7) {
								for (let i = 0; i < item.imgarr.length; i++) {
									let tmp = item.imgarr[i]
									await apiUpload.orderVideoUpload({ files: tmp.file }).then(res => {
										item.optVos.push({ id: null, optValue: res.data.rows[0] })
									})
								}
							} else {
								item.optVos = [{ id: null, optValue: item.value }]
							}
				}
				dataData.fieldVals = dataData.fieldVals.map(o => {
					return {
						"fieldId": o.fieldId,
						"id": o.id,
						"name": o.name,
						"optVos": o.optVos,
						"type": o.type
					}
				})
			}
			await apiNetwork.saveNetwork(dataData, inviteCode.value).then(async res => {
				if (res.code == 20000) {
					uni.hideLoading()
					uni.showToast({
						title: res.message,
						icon: 'success'
					})
					setTimeout(()=>{
						uni.redirectTo({
							url:"/pages/pages_network/login/role"
						})
					},1000)
				}
			})
			uni.hideLoading()
		}).catch(err => { })
	}
	// 获取企业信息
	const addCode = async (inviteCode) => {
		if (inviteCode) {
			uni.showLoading({
				title: "加载中...",
				mask: true
			})
			await apiNetwork.getCustomerInfo(inviteCode).then(res => {
				if (res.code == 20000) {
					networkMobileCreateVo.value = res.data.rows
					if (res.data.rows.networkFields.length > 0) {
						baseFormData.value.fieldVals = res.data.rows.networkFields.map((o) => {
							o.fieldId = o.id
							o.id = null
							o.contents = o.contents.map(i => {
								return {
									text: i.val,
									value: i.val
								}
							})
							if (o.type == 5 || o.type == 6 || o.type == 7) {
								o.imgarr = []
							} else if (o.type == 4) {
								o.value = []
							} else {
								o.value = ''
							}
							return o
						})
					}
				}
			})
			uni.hideLoading()
		}
	}
</script>

<style lang="scss" scoped>
	:deep(.tree-picker) {
		.uni-flex-item {
			display: flex;
			align-items: center;
			width: 100%;
			font-size: 28rpx;
		}
	}

	.mian {
		background-color: #fafafa;
		/* #ifdef H5 */
		height: calc(100vh - 44px);
		/* #endif */
		/* #ifndef H5 */
		height: 100vh;
		/* #endif */
		overflow-y: auto;

		:deep(.uni-modal__bd) {
			color: #F56C6C !important;
		}

		:deep(.uni-modal__btn_primary) {
			color: #F56C6C !important;
		}

		.title_customer {
			height: 80rpx;
			text-align: center;
			line-height: 80rpx;
			margin: 0 24rpx;
			font-size: 32rpx;
			font-weight: bold;
		}

		:deep(.uni-forms-item__label) {
			font-size: 28rpx;
		}

		:deep(.uni-easyinput__content-input) {
			font-size: 28rpx;
		}

		.uni_form {
			background-color: #fff;
			border-radius: 20rpx;
			padding: 10rpx 24rpx;
			margin: 0rpx 24rpx 400rpx;

			:deep(.uni-forms-item) {
				margin-bottom: 28rpx;
				padding: 8rpx 0;

				.uni-select {
					border: none;
					border-bottom:1rpx solid  #e5e5e5;
					border-radius: 0;
				}

				.show_input {
					border-bottom:1rpx solid  #e5e5e5;
				}

				.team_type {
					height: 100%;
					display: flex;
					align-items: center;
					margin-left: 20rpx;
				}

				.addressListStr_type {
					height: 100%;
					display: flex;
					align-items: center;
					justify-content: space-between;
					padding-left: 20rpx;
					border-bottom:1rpx solid  #e5e5e5;
					max-height: 280rpx;
					overflow: auto;

					.icon_btn {
						margin-right: 10rpx;
					}

					.tip {
						font-size: 28rpx;
						color: #999;
					}
				}
			}

			:deep(.uni-easyinput__content-textarea) {
				height: 100%;
				line-height: normal;
				min-height: 70rpx;
				max-height: 160rpx;
				margin: 0;
				line-height: 70rpx;
			}

			.pic_img {
				:deep(.icon-add) {
					width: 26rpx;
					height: 3rpx;
					background-color: #999;
				}

				:deep(.icon-del) {
					width: 24rpx;
				}

				:deep(.icon-del-box) {
					width: 40rpx;
					height: 40rpx;
					top: 0;
					right: 0;
					background-color: rgba(0, 0, 0, 0.3);
				}

				:deep(.file-picker__box-content) {
					.file-picker__progress {
						display: none !important;
					}
				}
			}

			.pic_video {
				display: flex;
				align-items: center;
				flex-wrap: wrap;

				.list_video {
					display: flex;
					align-items: center;
					flex-wrap: wrap;

					.box_video {
						width: 120rpx;
						height: 120rpx;
						margin-right: 20rpx;
						margin-bottom: 20rpx;
						position: relative;

						.clear_icon {
							position: absolute;
							top: 0;
							right: 0;
							z-index: 2;
							width: 40rpx;
							height: 40rpx;
							display: flex;
							align-items: center;
							justify-content: center;

							&:after {
								content: '';
								background-color: rgba(0, 0, 0, 0.3);
								position: absolute;
								top: 0;
								right: 0;
								z-index: -1;
								width: 40rpx;
								height: 40rpx;
								border-radius: 50%;
							}
						}

						.item_video {
							width: 100%;
							height: 100%;
						}
					}

					.box_video_pdf {
						width: 100rpx;
						height: 120rpx;
						margin-right: 20rpx;
						margin-bottom: 20rpx;
						position: relative;

						.pdf_sty {
							background-color: rgb(250, 81, 81);
							width: 100%;
							height: 100%;
							color: #fff;
							text-align: center;
							font-size: 22rpx;
							position: relative;
							display: flex;
							align-items: center;
							justify-content: center;

							&:before {
								content: '';
								position: absolute;
								z-index: 2;
								border: 12rpx solid #0000002b;
								right: 0rpx;
								top: 0rpx;
								border-top: 12rpx solid #fff;
								border-right: 12rpx solid #fff;
							}
						}

						.clear_icon {
							position: absolute;
							top: 0;
							right: 0;
							z-index: 4;
							width: 40rpx;
							height: 40rpx;
							display: flex;
							align-items: center;
							justify-content: center;

							&:after {
								content: '';
								background-color: rgba(0, 0, 0, 0.3);
								position: absolute;
								top: 0;
								right: 0;
								z-index: -1;
								width: 40rpx;
								height: 40rpx;
								border-radius: 50%;
							}
						}
					}
				}

				.btn_uploader {
					border: 1px solid #eeeeee;
					width: 120rpx;
					height: 120rpx;
					display: flex;
					justify-content: center;
					align-items: center;
					border-radius: 0;
					margin-right: 20rpx;
					margin-bottom: 20rpx;
					position: relative;
					overflow: hidden;

					.icon_plus {
						width: 100%;
						height: 100%;
						display: flex;
						justify-content: center;
						align-items: center;
					}

				}

				:deep(.uni-file-picker__files) {
					position: absolute;
					top: 0;
					right: 0;
					z-index: 4;
					width: 100%;
					height: 100%;
					opacity: 0;
				}
			}

			:deep(.is-input-border) {
				border: none;
				border-bottom: 1rpx solid transparent;
				border-radius: 0;

				&.is-focused {
					border-bottom: 1rpx solid #007cff99;

					.uniui-clear,
					.uniui-eye-filled {

						color: #007cff99 !important;
					}
				}
			}

		}

		.btn_word {
			padding: 50rpx;
			position: fixed;
			bottom: 0;
			left: 0;
			right: 0;
			z-index: 2;

			:deep(button:after) {
				border: none !important;
			}

			.btn_bor {
				// width: 50%;
				height: 80rpx;
				font-size: 28rpx;
				font-weight: bold;
				border-radius: 50rpx;
				background-color: #007cff;
				display: flex;
				align-items: center;
				justify-content: center;
			}
		}
	}
</style>